package cc.ycws.web.controller;

import cc.ycws.core.domain.Pay;
import cc.ycws.core.domain.Uploadfile;
import cc.ycws.core.service.PayService;
import cc.ycws.core.service.UploadfileService;
import cc.ycws.core.util.DataUtil;
import cc.ycws.core.util.HttpUtils;
import cc.ycws.core.util.SignUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/card")
public class CardController {

    private Logger logger = Logger.getLogger(CardController.class);
    private DataUtil d = new DataUtil();

    private String state_500 = "500";            //表示服务器内部错误
    private String state_0 = "0";                //表示请求服务器成功

    @Resource
    private UploadfileService uploadfileService;
    @Resource
    private PayService payService;

    /**
     * 根据用户输入的卡号,自动获取彩生活的小区地址,进行查询用户信息并返回结果
     *
     * @param cardnumber
     * @param community_name
     * @param modelmap
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/selectCard", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String selectCard(String cardnumber, String community_name, ModelMap modelmap) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        community_name = new String(community_name.getBytes("ISO-8859-1"), "utf-8");
        logger.info("小区地址:" + community_name);
        map.put("cardnumber", cardnumber);
        map.put("yaddress", community_name);
        map.put("deleteuser", "1");
        map.put("registrationandtype", "FastandRegistration");
        map.put("cardnumberandrepeat", "repeat");
        try {
            List<Uploadfile> uploadfile = this.uploadfileService.selectCard(map);
            modelmap.addAttribute("code", state_0);
            modelmap.addAttribute("list", uploadfile);
            JSONObject json = new JSONObject(modelmap);
            return json.toString();
        } catch (Exception e) {
            Map<String, Object> map2 = new HashMap<String, Object>();
            map2.put("code", state_500);
            JSONObject json = new JSONObject(map2);
            return json.toString();
        }
    }

    /**
     * 根据用户查询出来的卡号信息，进行支付所需费用后开启人脸识别门禁
     *
     * @param moblie
     * @param yphone
     * @param yid
     * @return
     */
    @ResponseBody
    @RequestMapping({"/buy"})
    public String buy(String moblie, String yphone, String yid) {
        String url = "https://openapi.colourlife.com/v1/gfjg/pay/unifiedorder";
        Map<String, String> testParam = new HashMap<String, String>();
        testParam.put("business_uuid", "e3ccf625-ee0e-44a4-b138-fa02859dea04");
        testParam.put("device_info", "CZYAPP");
        testParam.put("open_id", moblie);
        testParam.put("attach", "10yid" + yid + "phone" + yphone);
        testParam.put("mobile", yphone);
        testParam.put("nonce_str", DataUtil.getRandomString(40));
        testParam.put("body", "eanquan");
        testParam.put("detail", "123");
        testParam.put("out_trade_no", this.d.data() + moblie);
        testParam.put("total_fee", "1");
        testParam.put("meal_total_fee", "1");
        testParam.put("spbill_create_ip", "120.26.112.214");
        testParam.put("notify_url", "https://wwl.ycws.cc/h5/card/Notify");
        testParam.put("trade_type", "JSAPI");
        testParam.put("scene_info", "1000");
        testParam.put("sign", "397b9020a9dcf696466e8df24295bd73");
        testParam.put("ts", "1513996623");
        testParam.put("appID", "ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED");
        testParam.put("signature", SignUtils.getSignature(testParam));
        String md5 = SignUtils.getSignature(testParam);
        this.logger.info("统一下单接口,生成md5:" + md5);
        String param = SignUtils.buildParams(testParam);
        this.logger.info("请求参数:" + param);
        String responseStr = HttpUtils.sendPost(url, param);
        new JSONObject();
        JSONObject json = JSONObject.parseObject(responseStr);
        this.logger.info("下单返回结果:" + json);
        return json.toString();
    }

    @RequestMapping({"/Notify"})
    @ResponseBody
    public String Notify(HttpServletRequest request) throws Exception {
        BufferedReader reader = null;
        reader = request.getReader();
        String line = "";
        String xmlString = null;
        StringBuffer inputString = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            inputString.append(line);
        }
        xmlString = inputString.toString();
        if (xmlString != null) {
            this.logger.info("支付回调地址,接收到的数据如下:" + xmlString);
            String trade_state = "trade_state";
            String sub_srade_state = xmlString.substring(
                    xmlString.indexOf(trade_state),
                    xmlString.indexOf(trade_state) + trade_state.length() + 2);
            String state = sub_srade_state.substring(12, 13);
            if ((state.equals("2")) || (state.equals("3"))) {
                this.logger.info("交易成功");
                String attach = "attach";
                String open_id = "open_id";
                String sub_attach = xmlString.substring(
                        xmlString.indexOf(attach), xmlString.indexOf(attach)
                                + attach.length() + 3);
                String sub_open_id = xmlString.substring(
                        xmlString.indexOf(open_id), xmlString.indexOf(open_id)
                                + open_id.length() + 33);
                String sub_yid = xmlString.substring(
                        xmlString.indexOf("yid") + 3,
                        xmlString.indexOf("phone"));
                String mobile = xmlString.substring(
                        xmlString.indexOf("phone") + 5,
                        xmlString.indexOf("&time_pay"));
                int id = Integer.parseInt(sub_yid);
                String year = sub_attach.substring(7, 8);
                String number = sub_attach.substring(8, 9);
                String openid = sub_open_id.substring(8, 40);
                int Iyear = Integer.parseInt(year);
                int Inumber = Integer.parseInt(number);
                this.logger.info("id+" + id + "\t mobile" + mobile);

                Pay pay = new Pay();
                pay.setYear(Integer.valueOf(Iyear));
                pay.setNumber(Integer.valueOf(Inumber));
                pay.setTime(DataUtil.data1());
                pay.setState("1");
                pay.setUserid(openid);
                pay.setMoeny((Iyear + Inumber) * 30);
                pay.setTotal(Iyear + Inumber);
                try {
                    this.payService.insert(pay);
                } catch (Exception e) {
                    this.logger.info(e);
                }
                Uploadfile uploadfile = new Uploadfile();
                uploadfile.setYid(Integer.valueOf(id));
                Uploadfile user = this.uploadfileService.getid(uploadfile);
                int idnumber = Integer.parseInt(user.getIdnumber().substring(0,
                        4));
                String Syear = String.valueOf(idnumber + Iyear);
                uploadfile.setIdnumber(Syear
                        + user.getIdnumber().substring(4, 8));
                uploadfile.setYindex("1");
                uploadfile.setPayment("1");
                uploadfile.setUpdatetime(DataUtil.data1());
                uploadfile.setYphone(mobile);
                uploadfile.setUserid(openid);
                try {
                    this.uploadfileService.updateTimeCard(uploadfile);
                } catch (Exception e) {
                    this.logger.info(e);
                }
                return "SUCCESS";
            }
            this.logger.info("交易失败");
            return "FAIL";
        }
        this.logger.info("支付回调地址,数据为Null");
        return "FAIL";
    }

    /**
     * 支付成功返回界面
     *
     * @param modelMap
     * @param request
     * @return
     */
    @RequestMapping({"/returned"})
    public String returned(ModelMap modelMap, HttpServletRequest request) {
        String openid = request.getParameter("openid");
        String phone = request.getParameter("yphone");
        return "redirect:/p/success?userid=" + openid + "&yphone=" + phone.substring(0, 11);
    }
}
